﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace JQueryWidget.WidgetFrame
{
    public partial class AJAXFunc : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // System.Runtime.Serialization
            // System.ServiceModel
            // System.ServiceModel.Web
            // System.Runtime.Serialization.Json.DataContractJsonSerializer

            System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();  

            Response.Clear();
            if (!String.IsNullOrEmpty(Request["method"]))
            {
                Func<XElement, XName, string> getProperty = (element, name) => element.Element(name).Value; 

                switch (Request["method"])
                {
                    case "getWidgets":
                        var allWidgets = (from ele in XDocument.Load(Server.MapPath("~/Data/widgets.xml")).Element("widgets").Elements("widget")
                                          select
                                          new
                                          {
                                              ID = getProperty(ele, "id"),
                                              Title = getProperty(ele, "title"),
                                              Type = getProperty(ele, "type"),
                                              Src = getProperty(ele, "src")
                                          }).ToList();
                        Response.Write(jsSerializer.Serialize(allWidgets));
                        break;
                    case "getWidget":
                        string id = Request["id"];
                        var widget = (from ele in XDocument.Load(Server.MapPath("~/Data/widgets.xml")).Element("widgets").Elements("widget")
                                        where ele.Element("id").Value==id
                                        select
                                        new
                                        {
                                            ID = getProperty(ele, "id"),
                                            Title = getProperty(ele, "title"),
                                            Type = getProperty(ele, "type"),
                                            Src = getProperty(ele, "src")
                                        }).FirstOrDefault();
                        Response.Write(jsSerializer.Serialize(widget));
                        break; 

                    case "dragWidget":
                        Response.Write(DragWidget(Convert.ToInt32(Request["widgetid"]),
                                                   Convert.ToInt32(Request["index"]),
                                                   Request["columnid"],
                                                   Convert.ToInt32(Request["pageid"])));
                        break;

                    case "deleteWidget":
                        Response.Write(DeleteWidget(Convert.ToInt32(Request["widgetid"]),
                                                   Convert.ToInt32(Request["index"]),
                                                   Request["columnid"],
                                                   Convert.ToInt32(Request["pageid"])));
                        break;
                    case "moveWidget":
                        Response.Write(MoveWidget(Convert.ToInt32(Request["widgetid"]),
                                                  Convert.ToInt32(Request["index"]),
                                                  Request["columnid"],
                                                  Convert.ToInt32(Request["towidgetid"]),
                                                  Convert.ToInt32(Request["toindex"]),
                                                  Request["tocolumnid"],
                                                  Convert.ToInt32(Request["pageid"])));
                        break;
                    default :
                        Response.Write("Error");
                        break;
                }
            }
            else
            {
                Response.Write("Error");
            }
            Response.End();
        }

        protected bool DragWidget(int widgetid, int index, string columnid, int pageId)
        {
            try
            {
                var templatedataid = (from pagedata in XDocument.Load(Server.MapPath("~/Data/pagedata.xml")).Element("pages").Elements("page")
                                      where pagedata.Element("id").Value == pageId.ToString()
                                      select pagedata.Element("templatedataid").Value).FirstOrDefault();
                if (templatedataid != null)
                {
                    XDocument xDoc = XDocument.Load(Server.MapPath("~/Data/templatedata.xml"));
                    var templateData = (from td in xDoc.Element("templatedatas").Elements("templatedata")
                                        where td.Element("id").Value == templatedataid
                                        select td).FirstOrDefault();
                    if (templateData != null)
                    {
                        var columnData = (from cd in templateData.Element("columns").Elements("column")
                                          where cd.Attribute("id").Value == columnid
                                          select cd).FirstOrDefault();
                        if (columnData == null)
                        {
                            columnData = new XElement("column");
                            columnData.Add(new XAttribute("id", columnid));
                            columnData.Add(new XElement("widgets"));
                            templateData.Element("columns").Add(columnData);
                        }
                        var widget = new XElement("widget");
                        widget.Add(new XAttribute("id", widgetid.ToString()));
                        var widgets = columnData.Element("widgets");
                        if (widgets.Elements("widget").Count() > index)
                        {
                            widgets.Elements("widget").ElementAt(index).AddBeforeSelf(widget);
                        }
                        else
                        {
                            if (index > 0)
                            {
                                widgets.Elements("widget").ElementAt(index - 1).AddAfterSelf(widget);
                            }
                            else
                            {
                                widgets.Add(widget);
                            }
                        }

                        xDoc.Save(Server.MapPath("~/Data/templatedata.xml"));
                        return true;
                    }
                }
            }catch(Exception e)
            {}
            return false;
        }

        protected bool MoveWidget(int widgetid, int index, string columnid, int towidgetid, int toindex, string tocolumnid, int pageId)
        {
            try
            { 
                var templatedataid = (from pagedata in XDocument.Load(Server.MapPath("~/Data/pagedata.xml")).Element("pages").Elements("page")
                                      where pagedata.Element("id").Value == pageId.ToString()
                                      select pagedata.Element("templatedataid").Value).FirstOrDefault();
                if (templatedataid != null)
                {
                     XDocument xDoc = XDocument.Load(Server.MapPath("~/Data/templatedata.xml"));
                    var templateData = (from td in xDoc.Element("templatedatas").Elements("templatedata")
                                        where td.Element("id").Value == templatedataid
                                        select td).FirstOrDefault();
                    if (templateData != null)
                    {
                        var columnData = (from cd in templateData.Element("columns").Elements("column")
                                          where cd.Attribute("id").Value == columnid
                                          select cd
                                                ).FirstOrDefault();
                        if (columnData != null)
                        {
                            var widgetData = (from wd in columnData.Element("widgets").Elements("widget")
                                              select wd).ToList().ElementAtOrDefault(index);
                            if (widgetData != null)
                                widgetData.Remove();

                            //Save
                            columnData = (from cd in templateData.Element("columns").Elements("column")
                                          where cd.Attribute("id").Value == tocolumnid
                                          select cd).FirstOrDefault();
                            if (columnData == null)
                            {
                                columnData = new XElement("column");
                                columnData.Add(new XAttribute("id", tocolumnid));
                                columnData.Add(new XElement("widgets"));
                                templateData.Element("columns").Add(columnData);
                            }
                            var widget = widgetData;
                            var widgets = columnData.Element("widgets");
                            if (widgets.Elements("widget").Count() > toindex)
                            {
                                widgets.Elements("widget").ElementAt(toindex).AddBeforeSelf(widget);
                            }
                            else
                            {
                                if (toindex > 0)
                                {
                                    widgets.Elements("widget").ElementAt(toindex - 1).AddAfterSelf(widget);
                                }
                                else
                                {
                                    widgets.Add(widget);
                                }
                            }

                            xDoc.Save(Server.MapPath("~/Data/templatedata.xml"));
                            return true;
                        }                       

                    }
                }
            }
            catch (Exception e)
            { }
            return false;
        }
        
        protected bool DeleteWidget(int widgetid, int index, string columnid, int pageId)
        {
            try { 
                var templatedataid = (from pagedata in XDocument.Load(Server.MapPath("~/Data/pagedata.xml")).Element("pages").Elements("page")
                                      where pagedata.Element("id").Value == pageId.ToString()
                                      select pagedata.Element("templatedataid").Value).FirstOrDefault();
                if (templatedataid != null)
                {
                    XDocument xDoc = XDocument.Load(Server.MapPath("~/Data/templatedata.xml"));
                    var templateData = (from td in xDoc.Element("templatedatas").Elements("templatedata")
                                        where td.Element("id").Value == templatedataid
                                        select td).FirstOrDefault();
                    if (templateData != null)
                    {
                        var columnData = (from cd in templateData.Element("columns").Elements("column")
                                          where cd.Attribute("id").Value == columnid
                                          select cd).FirstOrDefault();

                        if (columnData != null)
                        {
                            var widgetData = (from wd in columnData.Element("widgets").Elements("widget")
                                              select wd).ToList().ElementAtOrDefault(index);
                            if (widgetData != null)
                            {
                                widgetData.Remove();
                                xDoc.Save(Server.MapPath("~/Data/templatedata.xml"));
                                return true;
                            }
                        }
                    }
                }
            
            }catch(Exception e)
            {
            }
            return false;
        }
    }
}